package com.toaa.crazymath.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.PatternSyntaxException;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;

import com.toaa.crazymath.controller.ResultPoint;

public class CommonUtils {

	public static List<ResultPoint> convertStringToBestPoints(String inputString) {
		if (!TextUtils.isEmpty(inputString)) {
			try {
				List<ResultPoint> resultPoints = new ArrayList<ResultPoint>();
				String[] splitString = inputString.split(",");
				for (int i = 0; i < splitString.length; i++) {
					final String[] resultStringArray = splitString[i].split("-");
					final int difficult = Integer.parseInt(resultStringArray[0]);
					final int bestPoint = Integer.parseInt(resultStringArray[1]);
					final ResultPoint resultPoint = new ResultPoint(difficult, bestPoint);
					resultPoints.add(resultPoint);
				}
				return resultPoints;
			} catch (PatternSyntaxException e) {
			}
		}
		return null;
	}
	
	public static String convertBestPointToString(List<ResultPoint> resultPoints) {
		final StringBuilder stringBuilder = new StringBuilder();
		for (ResultPoint resultPoint : resultPoints) {
			stringBuilder.append(String.format("%d-%d", resultPoint.getDifficult(), resultPoint.getBestPoint()));
			stringBuilder.append(",");
		}
		stringBuilder.deleteCharAt(stringBuilder.length() - 1);
		return stringBuilder.toString();
	}
	
	public static ResultPoint getResultPointByDifficult(List<ResultPoint> resultPoints, int difficult) {
		for (ResultPoint resultPoint : resultPoints) {
			if (difficult == resultPoint.getDifficult()) {
				return resultPoint;
			}
		}
		return null;
	}
	
	/**
	 * 
	 * @param activity
	 * @return
	 */
	public static Fragment getVisibleFragment(FragmentActivity activity){
	    FragmentManager fragmentManager = activity.getSupportFragmentManager();
	    List<Fragment> fragments = fragmentManager.getFragments();
	    for(Fragment fragment : fragments){
	        if(fragment != null && fragment.isVisible())
	            return fragment;
	    }
	    return null;
	}
	
	
}
